import pytest
import os
import logging
from app import create_app
from .config import TestConfig

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

@pytest.fixture
def app():
    """创建应用实例"""
    app = create_app()
    app.config['TESTING'] = True
    return app

@pytest.fixture
def client(app):
    """创建测试客户端"""
    return app.test_client()

@pytest.fixture
def logger():
    """创建测试日志器"""
    return logging.getLogger('test')

@pytest.fixture(autouse=True)
def setup_test_env(logger):
    """设置测试环境变量"""
    # 保存原始环境变量
    original_env = {}
    for key in TestConfig.DEFAULT_CONFIG.keys():
        original_env[key] = os.environ.get(key)
    
    # 加载测试配置
    test_config = TestConfig.load_config()
    os.environ.update(test_config)
    
    # 记录环境变量设置
    for key, value in test_config.items():
        logger.info(f"Set test environment variable {key}: {value[:4]}{'*' * 8 if len(value) > 4 else ''}")
    
    yield
    
    # 恢复原始环境变量
    for key, value in original_env.items():
        if value is None:
            os.environ.pop(key, None)
        else:
            os.environ[key] = value 